package com.woniuxy.sddfp.sms.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.woniuxy.sddfp.common.result.Result;
import com.woniuxy.sddfp.sms.config.SmsTemplate;
import com.woniuxy.sddfp.sms.service.ISmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;

/**
 * @author yellow Doctor
 * @date 2025-06-24
 * @desc 蜗牛创想：www.woniuxy.com
 */
@Service
public class SmsServiceImplPlus implements ISmsService {
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //发送短信
    /**
     * 01 给阿里云发送短信
     * 02 给redis中发送短信
     * @param mobile
     * @return
     */
    @Override
    public Result sendCode(String mobile) {

        //这里搞一个计数
        String countKey = "count:" + mobile;
        //这里加一个锁
        String lockKey = "lockKey:" + mobile;

        //01 随机一个验证码
        String code = RandomUtil.randomNumbers(4);

        //阿里云发送短信
//        smsTemplate.sendSms(mobile,code);

        //获取锁判断一下
        String lock = stringRedisTemplate.opsForValue().get(lockKey);
        if (StringUtils.hasText(lock)){
            return Result.ok("先不要获取短信、你的账户锁住了、联系管理员给你解锁...");
        }

        String count = stringRedisTemplate.opsForValue().get(countKey);

        //第一次 进行计数
        if (count==null){
            //统计次数
            stringRedisTemplate.opsForValue().set(
                    countKey,
                    "1",
                    Duration.ofMinutes(5)
            );
        }else {
            //第3次 进行加锁
            if (Integer.parseInt(count) >= 3) {
                //加锁
                stringRedisTemplate.opsForValue().set(
                        lockKey,
                        "lock",
                        Duration.ofHours(2)
                );
                return Result.ok("不要短时间搞短信轰炸、系统繁忙、我这里给你锁一下账号");
            }
            //每次发送成功 进行自增
            //increment 这个犯法是自增
            stringRedisTemplate.opsForValue().increment(countKey);
        }

        //给redis中发送短信
        String redisKey = "user:code:" + mobile;
        stringRedisTemplate.opsForValue().set(
                redisKey,
                code,
                Duration.ofMinutes(5)
        );

        return Result.ok("验证码是:" + code);
    }
}
